package com.itesm.distribuidos.mexicantrain;

import java.io.IOException;
import java.io.ObjectInputStream;
import java.net.InetAddress;
import java.net.InetSocketAddress;
import java.net.Socket;
import java.net.SocketAddress;

public class ServerListener extends Thread {
	private SocketAddress socketAddress;
	private MainGUI mainGUI;
	private Socket socket;

	public ServerListener(InetAddress address, MainGUI gui) {
		socketAddress = new InetSocketAddress(address,61000);
		mainGUI = gui;
	}

	public void run() {
		while(true) {
			try {
	    		socket = new Socket();
	    		socket.connect(socketAddress);
			    ObjectInputStream ois = new ObjectInputStream(socket.getInputStream());
			    Object data = ois.readObject();
			    if (data instanceof Integer) { mainGUI.updateTurn((Integer) data); }
			    if (data instanceof String)  { mainGUI.updateBoneyard(Integer.parseInt((String) data)); }
			    ois.close();
				socket.close();
			}
			catch (IOException ioe) { System.out.println("ServerListener - IO Error"); }
			catch (ClassNotFoundException cnfe) { System.out.println("ServerListener - Class Not Found Error"); }
		}
	}
}
